import { createStore } from 'vuex'

/*定义初始状态*/
const state = {
  user: null /*初始状态下没有登录用户*/
}

/*定义 mutations*/
const mutations = {
  setUser(state, username) {
    state.user = username
  },
  clearUser(state) {
    state.user = null
  }
}

/*定义 actions*/
const actions = {
  login({ commit }, username) {
    commit('setUser', username)
    localStorage.setItem('username', username) /*存储用户名到 localStorage*/
  },
  logout({ commit }) {
    commit('clearUser')
    localStorage.removeItem('username') /*从 localStorage 中移除用户名*/
  }
}

/*定义 getters*/
const getters = {
  currentUser: state => state.user
}

/*创建 store 实例*/
export default createStore({
  state,
  mutations,
  actions,
  getters
})
